package utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.naming.NamingException;

import utils.JNDIFactory;

import org.apache.log4j.Logger;



public class Database 
{
	private Connection conn = null;
	private Statement statement = null;

	private JNDIFactory jndiFactory = JNDIFactory.getInstance();
	private String db = null;
	private static Database instance;
	private static String dbName = "jdbc/waiDB";
	private static Logger jlog = Logger.getLogger(Database.class);
	private ResultSet rs;
	
	public Database(String db)
	{
		this.db = db;
	}

	
	
	public static Database getInstance()
	{
		if (instance == null)
			instance = new Database(dbName);
		return instance;
	}
	
	public void openConn()
	{
		jlog.debug("OpenConnection");
		try {
			conn = jndiFactory.getConnection(this.db);
			statement = conn.createStatement();
			
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			jlog.debug(e.getMessage());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			jlog.debug(e.getMessage());
		}
	}
	
	public void closeConn()
	{
		jlog.debug("CloseConnection");
		try {
			 conn.close();
			 statement.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			jlog.debug(e.getMessage());
		}
	}
	
	public ResultSet connect_and_execute(String sqlcmd)
	{
		String[] cmdArray = sqlcmd.split(" ");
		String cmd = cmdArray[0].toUpperCase();
		
		
		
		jlog.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		jlog.debug("WAIDB:" + this.db + " + SQL STATEMENT:" + sqlcmd);
		try
		{
//			conn = jndiFactory.getConnection(this.db);
//			
//			statement = conn.createStatement();
			if (cmd.endsWith("SELECT"))
			{
				this.rs = statement.executeQuery(sqlcmd);
			}
			else
			{
				statement.executeUpdate(sqlcmd);
			}
			
			return rs;
		}
		catch (Exception sqlex)
		{
			jlog.info("Exception SQL:" + sqlex.getMessage());
			
			if (conn != null)
				try {
					conn.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			if (statement != null)
				try {
					statement.close();
				} catch (Exception e) {
					e.printStackTrace();
				}

			return rs;
		}

		
	}
	

}
